package vip.zhenzicheng.concurrent_program.thread.sgg.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 线程中断demo
 *
 * @author zhenzicheng
 * @date 2022-06-27 17:58
 */
public class InterruptDemo {

  static volatile boolean isStop = false;
  static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

  public static void main(String[] args) {
    // m1_volatile();
    // m2_atomicBoolean();
    // m3_api();
  }

  private static void m3_api() {
    Thread t1 = new Thread(() -> {
      while (true) {
        if (Thread.currentThread().isInterrupted()) {
          System.out.println(Thread.currentThread().getName() + "\t isInterrupted() 被修改为 true，程序停止");
          break;
        }
        System.out.println("t1 ----hello interrupt api");
      }
    }, "t1");
    t1.start();

    try {
      TimeUnit.MILLISECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // t2希望t1停止
    new Thread(() -> {
      t1.interrupt();
    }, "t2").start();

    // t1 自己要停止
    // t1.interrupt();
  }

  private static void m2_atomicBoolean() {
    new Thread(() -> {
      while (true) {
        if (atomicBoolean.get()) {
          System.out.println(Thread.currentThread().getName() + "\t atomicBoolean 被修改为 true，程序停止");
          break;
        }
        System.out.println("t1 ----hello atomicBoolean");
      }
    }, "t1").start();

    try {
      TimeUnit.MILLISECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    new Thread(() -> {
      atomicBoolean.set(true);
    }, "t2").start();
  }

  private static void m1_volatile() {
    new Thread(() -> {
      while (true) {
        if (isStop) {
          System.out.println(Thread.currentThread().getName() + "\t isStop 被修改为 true，程序停止");
          break;
        }
        System.out.println("t1 ----hello volatile");
      }
    }, "t1").start();

    try {
      TimeUnit.MILLISECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    new Thread(() -> {
      isStop = true;
    }, "t2").start();
  }
}
